<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" formType="add" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <FilterTable
      ref="table"
      columnsRef="finance_repairFinance_receivables_receiptsDetail_table1"
      height="auto"
      :columns="columns"
      :isPagination="false"
      :fetchapi="fetchApi"
      :params="fetchParams"
      selectionType="single"
      :datakey="'rows'"
      :onCellChange="changeCells"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
      :onColumnsChange="columns => (this.columns = columns)"
    ></FilterTable>
    <FilterTable
      ref="table1"
      columnsRef="finance_repairFinance_receivables_receiptsDetail_table2"
      height="auto"
      :isPagination="false"
      :columns="columns1"
      :fetchapi="fetchApi1"
      :params="fetchParams1"
      selectionType="single"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns1 = columns)"
      style="margin-top:10px"
      :onSyncTableData="tableHandle"
    ></FilterTable>
    <FilterTable
      ref="table2"
      columnsRef="finance_repairFinance_receivables_receiptsDetail_table3"
      height="auto"
      :isPagination="false"
      :columns="columns2"
      :fetchapi="fetchApi2"
      :params="fetchParams2"
      selectionType="single"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns2 = columns)"
      style="margin-top:10px"
    ></FilterTable>
    <!-- 打印 -->
    <div v-if="printFlag">
      <BasePrint ref="print" :data="printList" template="templateReceiptsDetail" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button type="primary" @click="printClick">打印收据</el-button>
      <el-button type="primary" :disabled="disable" @click="saveChange">确 定</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import { addRole } from '@/api/common/auth/roleManage';
import { getDealerUser, getReceiptRecord, getReceiptsDetail, getReductionRecord, getInvoiceType, editSave, getInvoiceList, gatheringManage } from '@/api/finance/repair/receivables';
import * as types from '@/api/common/auth/roleManage/types';
import { getAllUser } from '@/api/finance/advancesReceived/register';
import moment from 'moment';
export default {
  name: 'ReceiptsDetail',
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return {
      index: null,
      formList: this.createFormList(),
      columns: this.createTableColumns(),
      columns1: this.createTableColumns1(),
      columns2: this.createTableColumns2(),
      fetchApi: getReceiptRecord,
      fetchApi1: getReductionRecord,
      fetchApi2: getInvoiceList,
      fetchParams: { xhrAbort: true },
      fetchParams1: { xhrAbort: true },
      fetchParams2: { xhrAbort: true },
      disable: true,
      selectColumns: [],
      printList: {},
      printFlag: true,
      tableData: []
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    addBtnState() {
      return this.btnLoading[types.YAN_ROLE_ADD];
    }
  },
  created() {
    if (this.type === 'edit') {
      this.formList.forEach(x => {
        x.initialValue = this.rowData[x.fieldName];
      });
    }
  },
  mounted() {
    this.serviceConsultant(); // 服务顾问下拉
    this.getInvoiceType(); // 发票类型下拉
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'LICENSE',
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'VIN',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主编号',
          fieldName: 'OWNER_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'OWNER_NAME',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'RO_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '备件销售单号',
          fieldName: 'SALES_PART_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'BALANCE_NO',
          disabled: true
        },
        {
          type: 'SELECT',
          itemList: [],
          label: '服务顾问',
          fieldName: 'SERVICE_ADVISOR',
          disabled: true
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '收款单号',
          dataIndex: 'RECEIVE_NO',
          sorter: true
        },
        {
          title: '收款日期',
          dataIndex: 'RECEIVE_DATE',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true,
          width: 150
        },
        {
          title: '收款金额',
          dataIndex: 'RECEIVE_AMOUNT',
          sorter: true,
          precision: 2
        },
        {
          title: '销帐标志',
          dataIndex: 'WRITEOFF_TAG',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.WRITEOFF_TAG, '1004')}</span>;
          }
        },
        {
          title: '经手人',
          dataIndex: 'HANDLER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '付款方式',
          dataIndex: 'PAY_TYPE_CODE',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.PAY_TYPE_CODE, '8044')}</span>;
          }
        },
        {
          title: '本次使用余款',
          dataIndex: 'PAYOUT_AMOUNT',
          sorter: true
        },
        {
          title: '已开票',
          dataIndex: 'INVOICE_TAG',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.INVOICE_TAG, '1004')}</span>;
          }
        },
        {
          title: '是否全部开票',
          dataIndex: 'IS_ALL_INVOICE',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.IS_ALL_INVOICE, '1004')}</span>;
          }
        },
        // {
        //   title: '发票类型',
        //   dataIndex: 'INVOICE_TYPE_CODE',
        //   sorter: true,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'select',
        //   editItems: []
        // },
        // {
        //   title: '票据号码',
        //   dataIndex: 'BILL_NO',
        //   sorter: true,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'input',
        // },
        // {
        //   title: '开票人',
        //   dataIndex: 'INVOICE_MAKER_NAME',
        //   sorter: true
        // },
        {
          title: '支票号码',
          dataIndex: 'CHECK_NO',
          sorter: true
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          editable: true,
          defaultEditable: true,
          editType: 'input'
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '减免单号',
          dataIndex: 'DERATE_NO',
          sorter: true
        },
        {
          title: '减免金额',
          dataIndex: 'DERATE_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '减免日期',
          dataIndex: 'DERATE_DATE',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true,
          width: 150
        },
        {
          title: '减免批准人',
          dataIndex: 'DERATE_RATIFIER',
          sorter: true
        },
        {
          title: '经手人',
          dataIndex: 'HANDLER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true
        }
      ];
    },
    createTableColumns2() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '发票类型',
          dataIndex: 'INVOICE_TYPE_CODE',
          sorter: true,
          width: 120,
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '发票金额',
          dataIndex: 'INVOICE_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '发票号',
          dataIndex: 'INVOICE_NO',
          sorter: true
        },
        {
          title: '发票日期',
          dataIndex: 'INVOICE_DATE',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          width: 150
        },
        {
          title: '发票客户',
          dataIndex: 'CUSTOMER_NAME',
          sorter: true
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true
        }
      ];
    },
    openModel(data) {
      // console.log(data.OWNER_CODE)
      this.getReceiptRecord(data.BALA_PAYOBJ_ID, data.OWNER_CODE); // 收款记录列表
      this.getReductionRecord(data.BALA_PAYOBJ_ID, data.OWNER_CODE); // 减免记录列表
      this.getReceiptsDetail(data.BALANCE_NO, data.OWNER_CODE); // 收款明细表单
      this.getInvoiceList(data.BALA_PAYOBJ_ID, data.OWNER_CODE); // 发票列表
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async serviceConsultant() {
      const res = await getDealerUser();
      console.log(res, '所有用户');
      this.columns.find(item => item.dataIndex === 'HANDLER').editItems = this.columns1.find(item => item.dataIndex === 'HANDLER').editItems = this.formList.find(
        item => item.fieldName === 'SERVICE_ADVISOR'
      ).itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    async getReceiptRecord(id, code) {
      const res = await getReceiptRecord(id, code);
      // console.log(res)
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(res.data);
    },
    async getReductionRecord(id, code) {
      const res = await getReductionRecord(id, code);
      // console.log(res)
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(res.data);
    },
    async getInvoiceList(id, code) {
      const res = await getInvoiceList(id, code);
      // console.log(res)
      this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(res.data);
    },
    async getReceiptsDetail(id, code) {
      const res = await getReceiptsDetail(id, code);
      // console.log('res',res)
      for (let [key, value] of Object.entries(res.data)) {
        this.formList.some(item => {
          if (item.fieldName === key) {
            item.initialValue = value;
            return true;
          }
        });
      }
    },
    async getInvoiceType() {
      const res = await getInvoiceType();
      // console.log(res)
      this.columns2.find(item => item.dataIndex === 'INVOICE_TYPE_CODE').editItems = res.data.map(x => ({ value: x.INVOICE_TYPE_CODE, text: x.INVOICE_TYPE_NAME }));
    },
    async saveChange() {
      let data = {
        gatheringList: this.$refs.table.$refs.pageTable.dataSource,
        remark: 'edit'
      };
      console.log('data', data);
      this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await editSave(data);
          // console.log("res",res)
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '保存成功!' });
            this.closeDialog();
          }
          this.deleteRows = [];
        })
        .catch(() => {});
    },
    closeDialog() {
      this.$emit('close', false);
    },
    changeCells(keys, obj) {
      this.disable = false;
    },

    // 打印
    async printClick() {
      if (this.selectColumns.length) {
        // this.printFlag = false;
        console.log(this.selectColumns, 'selectColumns');
        console.log(this.tableData, '减免金额的数据-----');
        let deratedAmount = 0;
        if (this.tableData.length !== 0) {
          this.tableData.forEach(x => {
            deratedAmount += Number(x.DERATE_AMOUNT);
          });
        }
        console.log(deratedAmount, '减免金额----');
        this.printList['BALANCE_NO'] = this.formList.find(item => item.fieldName === 'BALANCE_NO').initialValue;
        this.printList['OWNER_NAME'] = this.formList.find(item => item.fieldName === 'OWNER_NAME').initialValue;
        this.printList['VIN'] = this.formList.find(item => item.fieldName === 'VIN').initialValue;
        this.printList['RECEIVE_DATE'] = !this.selectColumns[0].RECEIVE_DATE ? '' : moment(this.selectColumns[0].RECEIVE_DATE).format('YYYY-MM-DD HH:mm:ss');
        this.printList['RECEIVE_NO'] = this.selectColumns[0].RECEIVE_NO;
        this.printList['PAY_TYPE_CODE'] = this.createDictText(this.selectColumns[0].PAY_TYPE_CODE, '8044');
        this.printList['PAYOUT_AMOUNT'] = Number(this.selectColumns[0].PAYOUT_AMOUNT).toFixed(2);
        this.printList['RECEIVE_AMOUNT'] = Number(this.selectColumns[0].RECEIVE_AMOUNT).toFixed(2);
        this.printList['DERATE_AMOUNT'] = Number(deratedAmount).toFixed(2);

        // let receiveNo = this.selectColumns[0]['RECEIVE_NO'];
        // const res = await gatheringManage(receiveNo);
        // console.log(res, 'res----');
        // this.printList = res.data;
        // this.printList['PAY_TYPE_CODE'] = this.createDictText(res.data.PAY_TYPE_CODE, '8044');
        this.printFlag = true;
        this.$nextTick(() => {
          this.$refs.print.EXCUTE_PRINT();
        });
      } else {
        this.$notify.warning({ title: '提示信息', message: '请选择表格数据!' });
      }
    },
    // table动态回调函数
    tableHandle(val) {
      this.tableData = val;
    }
  }
};
</script>

<style lang="less" scoped></style>
